package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorMapper flavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    public DishVO selectById(Long id) {
        DishDTO dish=new DishDTO();
        dish.setId(id);
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dishMapper.select(dish).get(0),dishVO);
        return dishVO;
    }

    /**
     * 新增分类
     * @param dishDTO
     */
    @Transactional
    public void addDishAndFlavor(DishDTO dishDTO){

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //想菜品表插入1条数据
        dishMapper.insert(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });

            //向口味表插入n条数据
            flavorMapper.insert(flavors);
        }

    }

    /**
     * 通过套餐ID查询菜品
     */
    @Override
    public List<DishVO> selectByCategoryId(String categoryId) {
        // 1. 创建查询条件对象
        DishDTO dishDTO = new DishDTO();
        dishDTO.setCategoryId(Long.valueOf(categoryId));

        // 2. 查询并转换为VO对象
        return dishMapper.select(dishDTO).stream()
                .map(dish -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(dish, dishVO);
                    return dishVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 分页查询菜品
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        //不能删除：存在起售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) { //状态为1起售中
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //不能删除：菜品被套餐关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.delete(id);
            //删除口味数据
            flavorMapper.deleteByDishId(id);
        }
    }


    /**
     * 通过Id查询菜品（修改时用于显示）
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.getById(id);
        DishVO dishVO=new DishVO();

        //填充基本信息
        BeanUtils.copyProperties(dish,dishVO);

        //填充口味信息
        List<DishFlavor> list=flavorMapper.selectFlavorByDishId(id);
        dishVO.setFlavors(list);

        return dishVO;
    }


    /**
     * 修改菜品
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //对于口味，先删除所有该菜品下的口味，再导入新的口味
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        flavorMapper.deleteByDishId(dish.getId());
        List<DishFlavor> flavors=flavorMapper.selectFlavorByDishId(dish.getId());

        //口味需要后插入菜品Id
        if(flavors != null && flavors.size()>0){
            flavors.forEach(dishFlavor ->{
                dishFlavor.setDishId(dishDTO.getId());
            });
            //mapper中的insert不判空，需要此处判空
            flavorMapper.insert(flavors);
        }
    }


}
